package org.dousb.doupicturebackend.manager.sharding;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

/**
 * 分库分表算法
 */
@Service
public class PictureShardingAlgorithm implements StandardShardingAlgorithm<Long> {

    @Override
    public void init(Properties props) {
        // 初始化操作（如读取配置）
    }

    @Override
    public Properties getProps() {
        return new Properties();
    }

    /**
     * 执行分片操作的方法
     *
     * @param availableTargetNames 可用的目标数据源或表名的集合
     * @param preciseShardingValue 精准分片值，包含分片键和值
     * @return 返回实际的目标表名
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {
        // 从分片值中获取空间ID
        Long spaceId = preciseShardingValue.getValue();
        // 从分片值中获取逻辑表名
        String logicTableName = preciseShardingValue.getLogicTableName();
        // 如果空间ID为空，直接返回逻辑表名
        if (spaceId == null) {
            return logicTableName;
        }
        //根据空间id动态生成表名
        String realTableName = "picture_" + spaceId;
        if (availableTargetNames.contains(realTableName)) {
            return realTableName;
        } else {
            return logicTableName;
        }

    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        return new ArrayList<>();
    }
}
